<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\BaseAdminController;
use App\Lib\Common;
use App\Lib\Enum\ValRule;
use App\Lib\Logger;
use App\Lib\Validates;
use App\Models\Admin\Menu;
use App\Rules\CheckRule;
use App\Service\AuthService;
use App\Service\MenuService;
use Illuminate\Http\Request;

class MenuController extends BaseAdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $data = (new MenuService())->list($request->all());
        return view("admin.menu.index", ["error"=>array_key_exists('error',$data)?$data['error']:0,"menuTable" => json_encode($data)]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request) {
        $params = (new CheckRule($request->all(), ValRule::PARENTID, ValRule::PARENTID_MSG))->check();
        if ($params["error"] > 0) {
            return $this->error($params['error'], $params['msg']);
        }
        //获取父栏目名称
        $result = (new AuthService())->getParent($params["data"]["parent_id"]);
        //结果处理
        return view("admin.menu.create", ["parent" => $result]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $params = $request->all();
        //是否需要验证路由
        if ($params["is_link"] != 1 && ($params["uri"] != null || !empty($params["uri"]) || $params["uri"] != "")) {
            $check=(new AuthService())->checkMenuRoute($params);
            if($check["error"]>0){
                return $this->error($check['error'], $check["msg"]);
            }
            $params=$check["data"];
        }
        //插入
        $result = (new Menu())->store($params);
        if(!empty($result)){
            $this->log(Logger::LOG_LEVEL_INFO,Logger::MENU,'store','添加成功',$result);
            return $this->success($result, "添加成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR,Logger::MENU,'store','添加失败',$params);
        return $this->error(70000, "添加失败");
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.menu.index","id必须是正整数","error");
        }
        //获取修改菜单
        $result = (new MenuService())->getOne($id);
        //获取已有菜单
        $menus=(new MenuService())->tree();
        return view("admin.menu.edit", ["menu" => $result, "menus" => json_encode($menus)]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id) {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.menu.index","id必须是正整数","error");
        }
        $params = $request->all();
        //是否需要验证路由
        if ($params["is_link"] != 1 && ($params["uri"] != null || !empty($params["uri"]) || $params["uri"] != "")) {
            $check=(new AuthService())->checkMenuRoute($params);
            if($check["error"]>0){
                return $this->error($check['error'], $check["msg"]);
            }
            $params=$check["data"];
        }
        //保存
        $result = (new Menu())->updateMenu($params, $id);
        if($result){
            $this->log(Logger::LOG_LEVEL_INFO,Logger::MENU,'update','更新成功',$params);
            return $this->success("","更新成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR,Logger::MENU,'update','更新失败',$params);
        return $this->error(80000, "更新失败");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.menu.index","id必须是正整数","error");
        }
        //删除
        $result = (new Menu())->destoryOne($id);
        if($result){
            $this->log(Logger::LOG_LEVEL_INFO,Logger::MENU,'destroy','删除成功',['del_id'=>$id]);
            return $this->layuiDataSuccess("",0,0,"删除成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR,Logger::MENU,'destroy','删除失败',['del_id'=>$id]);
        return $this->layuiDataError(80001,"删除失败");
    }

    /**
     * 检查路由是否存在
     */
    public function check_route(Request $request) {
        $result = (new AuthService())->check_permission_name($request->all()["data"]["name"], $this->getSiteId());
        return !empty($result)?$this->success($result,"路由权限存在，可以添加"):$this->error(70000,"没有对应路由权限，不可以添加");
    }

    /**
     * 排序
     */
    public function setSort($id,$sort){
        //验证
        $params = (new CheckRule(["id"=>$id,"sort"=>$sort], ValRule::SORT, ValRule::SORT_MSG))->check();
        if ($params["error"] > 0) {
            return $this->error($params['error'], $params['msg']);
        }
        //排序
        $result = (new MenuService())->setSort($id,$sort);
        if ($result) {
            $this->log(Logger::LOG_LEVEL_INFO, Logger::CATEGORY, 'setSort', "分类[ID:{$id}]更新排序,成功", "");
            return $this->success("", "排序更新成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::CATEGORY, 'setSort', "分类[ID:{$id}]更新排序,失败", "");
        return $this->error(80000, "排序更新失败");
    }
}
